let cacheVersion = 'cacheTest';
let cacheList = [
  './1.html',
  './2.html'
];

self.addEventListener('install', function (e) {
  console.log('service worker: 遇到安装');
  e.waitUntil(
    caches.open(cacheVersion).then(function (cache) {
      return cache.addAll(cacheList);
    })
  )
})
self.addEventListener('activate', function (e) {
  console.log('service worker: run into activate');
  e.waitUntil(
    caches.keys().then(function (cacheNames) {
      return Promise.all(cacheNames.map(function (cacheName) {
        if (cacheName !== cacheVersion) {
          console.log('service worker: clear cache' + cacheName);
          return caches.delete(cacheName)
        }
      }))
    })
  )
})
self.addEventListener('fetch', function (e) {
  e.respondWith(caches.match(e.request).then(function (response) {
    if (response) {
      console.log('service worker 匹配并读取缓存：' + event.request.url);
      return response;
    }
    console.log('没有匹配上：' + event.request.url);
    let fetchRequest = e.request.clone();
    return fetch(event.request).then(function (res) {
      if(!response || response.status !== 200 || response.type !== 'basic'){
        return response;
      }
      let responseToCache = response.clone();
      caches.open(cacheVersion).then(function (cache) {
        console.log(cache);
        cache.put(fetchRequest,responseToCache)
      })
    })
  }))
})
